<?php
/**
 * update部门
 */
apf_require_controller("HrAbstract");

class Hr_Ajax_UpdateDepartmentController extends HrAbstractController {

    public function handle_request() {
        $params = $this->request->get_parameters();
        $dep_id = intval($params['id']);
        $status = 0;
        if(empty($dep_id)){
            $this->json_encode($status,Const_Tip::ERROR_PARAM);
        }
        $costcity = trim($params['costcity']);
        $city_id = $this->_check_city($costcity);
        if(!$city_id){
            $this->json_encode($status,Const_Tip::ERROR_CITY_ERROR);
        }
        //参数验证
        $this->_check_params($params);
        $dep_bll = new Bll_Hr_Department();
        $dep_data = $dep_bll->find_dep_by_id($dep_id);
        if(empty($dep_data)){
            $this->json_encode($status,Const_Tip::ERROR_PARAM);
        }

        $indata = array(
                'company_id'=>$dep_data['company_id'],
                'city_id'=>$city_id,
                'function_id'=>$dep_data['function_id'],
                'bu_id'=>$dep_data['bu_id'],
                'department_name'=>trim($params['depart']),
        );
        //check 未被删除的同名部门
        $check_same = $dep_bll->check_same_department($indata);
        if(!empty($check_same) && $check_same!=$dep_id){
            $this->json_encode(0,Const_Tip::ERROR_DEPARTMENT_EXISTS);
        }
        $data = array(
            'department_name'=>trim($params['depart']),
            'cost_city'=>$city_id,
            'plan_num'=>intval($params['formation']),
        );
        $status = $dep_bll->update_department($dep_id,$data);
        $this->json_encode(1,Const_Tip::OPT_SUCCESS);
    }
    /**
     * 检测城市
     * @param string $city_name
     * @return number|mixed
     */
    private function _check_city($city_name){
        $re_city_id = 0;
        $pro_bll = new Bll_Hr_Property();
        $city_list = $pro_bll->get_sort_city_list();
        $city_id = array_search($city_name,$city_list);
        if($city_id===false){
            return $re_city_id;
        }
        return $city_id;
    }
    /**
     * 参数检测
     */
    private function _check_params($params){
        $depart = $params['depart'];
        $status=0;
        if(empty($depart)){
            $this->json_encode($status,Const_Tip::ERROR_PARAM);
        }
        $params['formation'] = intval($params['formation']);
        //城市传的是名字
        if($params['formation'] < 0 || $params['formation'] >100000){
            $this->json_encode($status,Const_Tip::ERROR_DEPARTMENT_PLAN_NUM);
        }
        if(mb_strlen($depart,'UTF-8') >10){
            $this->json_encode($status,Const_Tip::ERROR_DEPARTMENT_LENGTH);
        }
        return true;
    }
}